#!/usr/bin/env bash

#
#   $ curl -fsSL lnmp.khs1994.com -o lnmp.sh ; sh lnmp.sh
#
# CN mirror
#   $ curl -fsSL lnmp.khs1994.com -o lnmp.sh ; sh lnmp.sh --mirror gitee
#
# Support Documents
#
# https://docs.lnmp.khs1994.com/
#

rm -rf lnmp-test

LNMP_GIT_SSH_URL=git@github.com:khs1994-docker/lnmp.git

LNMP_GIT_HTTPS_URL=https://github.com/khs1994-docker/lnmp

LNMP_PATH=lnmp

help(){
  exec echo "

$ curl -fsSL lnmp.khs1994.com -o lnmp.sh ; sh lnmp.sh

CN mirror

$ curl -fsSL lnmp.khs1994.com -o lnmp.sh ; sh lnmp.sh --mirror aliyun | coding | tgit | gitee

Support Documents

https://docs.lnmp.khs1994.com/
"
}

clone_ssh(){
  echo "Clone by SSH way"
  git clone --recursive ${LNMP_GIT_SSH_URL} $LNMP_PATH \
    && (cd $LNMP_PATH ; git remote add lnmp ${LNMP_GIT_SSH_URL} ; git remote -v )
}

clone_https(){
  echo "Clone by SSH way is failure, try HTTPS way"
  git clone --recursive ${LNMP_GIT_HTTPS_URL} $LNMP_PATH \
    && (cd $LNMP_PATH ; git remote add lnmp ${LNMP_GIT_HTTPS_URL} ; git remote -v )
}

wget_git(){
  echo "Download by wget way"
  wget "${LNMP_GIT_HTTPS_URL}/archive/master.zip" -O $LNMP_PATH.zip
  unzip -o $LNMP_PATH.zip -d $LNMP_PATH >/dev/null 2>&1
  cd $LNMP_PATH
  cp -a lnmp-master/. .
  rm -rf lnmp-master ../$LNMP_PATH.zip
  success
}

exist_path() {
  if [ -d "$1" ] || [ -f "$1" ];then
    echo "$1 exists
==============================="
    read -p "Please input path: " LNMP_PATH
    if [ -z "$LNMP_PATH" ];then exit 1; fi
    exist_path $LNMP_PATH
  fi
}

success(){
  echo "==================================
==========  SUCCESS ==============
=================================="

  # cd $LNMP_PATH
  # which bash 2>&1 >/dev/null
  # if ! [ $? -eq 0 ];then sed -i "s/bin\/bash/bin\/sh/g" lnmp-docker; fi

  echo "Success please exec

$ cd ${LNMP_PATH}
"
exec echo "$ ./lnmp-docker up"
}

error(){
  exec echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!  ERROR  !!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
}

clone(){
    clone_ssh
    if [ $? -eq 0 ];then
      success
    else
      clone_https
      if [ $? -eq 0 ];then success; else error; fi
    fi
}

mirror(){
case $1 in
  gitee )
  LNMP_GIT_SSH_URL=git@gitee.com:khs1994/lnmp.git
  LNMP_GIT_HTTPS_URL=https://gitee.com/khs1994/lnmp
  ;;
  * )
  LNMP_GIT_SSH_URL=git@gitee.com:khs1994/lnmp.git
  LNMP_GIT_HTTPS_URL=https://gitee.com/khs1994/lnmp
  ;;
esac
}

echo "Welcome use khs1994-docker/lnmp"

case $1 in
  wget )
    exist_path
    wget_git
    ;;

  --mirror )
    exist_path
    mirror $2
    ;;

  --help | help | -h )
     help
     ;;

  * )
  echo > /dev/null 2>&1
    ;;
esac

exist_path $LNMP_PATH

command -v git >/dev/null 2>&1

if [ $? -eq 0 ];then
  clone
else
  wget_git
fi

# WebSite https://github.com/khs1994-docker/lnmp
# Support Documents https://docs.lnmp.khs1994.com/
# License Apache License Version 2.0
